package com.hrt.db;

import com.btcode.common.MyLog;
import com.btcode.db.config.DataBaseConfig;
import com.btcode.db.connection.IConnectionGetter;
import com.btcode.log.ILog;

import java.sql.Connection;
import java.sql.DriverManager;

public class ConnectionGetterForMysql implements IConnectionGetter {

    private ILog log = MyLog.getInstance().getLogger(getClass());
    private DataBaseConfig config;
    private ThreadLocal<Connection> connectionThread = new ThreadLocal<>();

    public ConnectionGetterForMysql(DataBaseConfig config) {
        this.config = config;
        if (config.isLog()) {
            log.logOn();
        } 
        else {
            log.logOff();
        }
    }

    @Override
    public Connection getConnection() {
        try {

            Connection connection = connectionThread.get();

            if (connection != null && !connection.isClosed()) {
                return connection;
            }

            connectionThread.remove();
            Class.forName(config.getDirverClass()).newInstance();
            connection = DriverManager.getConnection(config.getConnectionString(), config.getUserName(),
                    config.getPassword());
            connectionThread.set(connection);

            return connection;
        } 
        catch (Exception e) {
            e.printStackTrace();
            log.error("获取连接失败", e);
        }
        return null;
    }

    @Override
    public void close() {

    }

}
